package com.example.managemyself.ui.roulette;

import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;

import com.example.managemyself.R;
import com.example.managemyself.util.DeepSeekHelper;

import java.util.Random;

public class RouletteFragment extends Fragment {

    private ImageView ivRoulette;
    private Button btnSpin;
    private Button btnInterpret;
    private TextView tvSpinStatus;
    private TextView tvFirstResult;
    private TextView tvSecondResult;
    private TextView tvFinalResult;
    private LinearLayout layoutResults;
    private RadioGroup rgQuestionType;
    private EditText etQuestion;
    
    private Random random = new Random();
    private int spinCount = 0;
    private String firstGua = "";
    private String secondGua = "";
    private String finalGua = "";
    private String questionType = "是什么";

    // 八卦名称数组
    private final String[] bagua = {"乾", "巽", "离", "震", "艮", "兑", "坎", "坤"};
    
    // 八卦属性
    private final String[] baguaAttributes = {
        "天", "风", "火",  "雷", "山", "泽", "水", "地"
    };
    
    // 六十四卦名称
    private final String[] hexagrams = {
        "乾为天", "坤为地", "水雷屯", "山水蒙", "水天需", "天水讼", "地水师", "水地比",
        "风天小畜", "天泽履", "地天泰", "天地否", "天火同人", "火天大有", "地山谦", "雷地豫",
        "泽雷随", "山风蛊", "地泽临", "风地观", "火雷噬嗑", "山火贲", "山地剥", "地雷复",
        "天雷无妄", "山天大畜", "山雷颐", "泽风大过", "坎为水", "离为火", "泽山咸", "雷风恒",
        "天山遁", "雷天大壮", "火地晋", "地火明夷", "风火家人", "火泽睽", "水山蹇", "雷水解",
        "山泽损", "风雷益", "泽天夬", "天风姤", "泽地萃", "地风升", "泽水困", "水风井",
        "泽火革", "火风鼎", "震为雷", "艮为山", "风山渐", "雷泽归妹", "雷火丰", "火山旅",
        "巽为风", "兑为泽", "风水涣", "水泽节", "风泽中孚", "雷山小过", "水火既济", "火水未济"
    };
    
    // 六十四卦编号 (组合的八卦索引)
    private final int[][] hexagramIndices = {
        {0, 0}, {7, 7}, {6, 3}, {4, 6}, {6, 0}, {0, 6}, {7, 6}, {6, 7},
        {1, 0}, {0, 7}, {7, 0}, {0, 7}, {0, 2}, {2, 0}, {7, 4}, {3, 7},
        {7, 3}, {4, 1}, {7, 7}, {1, 7}, {2, 3}, {4, 2}, {4, 7}, {7, 3},
        {0, 3}, {4, 0}, {4, 3}, {7, 1}, {6, 6}, {2, 2}, {7, 4}, {3, 1},
        {0, 4}, {3, 0}, {2, 7}, {7, 2}, {1, 2}, {2, 7}, {6, 4}, {3, 6},
        {4, 7}, {1, 3}, {7, 0}, {0, 1}, {7, 7}, {7, 1}, {7, 6}, {6, 1},
        {7, 2}, {2, 1}, {3, 3}, {4, 4}, {1, 4}, {3, 7}, {3, 2}, {2, 4},
        {1, 1}, {7, 7}, {1, 6}, {6, 7}, {1, 7}, {3, 4}, {6, 2}, {2, 6}
    };

    private Handler timeoutHandler = new Handler();
    private Runnable timeoutRunnable;
    private ObjectAnimator currentAnimator;
    private static final long TIMEOUT_DURATION = 60000; // 60 seconds (1 minute)

    public RouletteFragment() {
        // 必须有一个空的公共构造函数
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_roulette, container, false);
        
        // 初始化视图
        ivRoulette = view.findViewById(R.id.ivRoulette);
        btnSpin = view.findViewById(R.id.btnSpin);
        tvSpinStatus = view.findViewById(R.id.tvSpinStatus);
        tvFirstResult = view.findViewById(R.id.tvFirstResult);
        tvSecondResult = view.findViewById(R.id.tvSecondResult);
        tvFinalResult = view.findViewById(R.id.tvFinalResult);
        layoutResults = view.findViewById(R.id.layoutResults);
        btnInterpret = view.findViewById(R.id.btnInterpret);
        rgQuestionType = view.findViewById(R.id.rgQuestionType);
        etQuestion = view.findViewById(R.id.etQuestion);
        
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        // 设置旋转按钮点击事件
        btnSpin.setOnClickListener(v -> spinRoulette());
        
        // 设置解卦按钮点击事件
        btnInterpret.setOnClickListener(v -> interpretHexagram());
        
        // 设置问题类型选择监听
        rgQuestionType.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.rbWhatIs) {
                questionType = "是什么";
            } else if (checkedId == R.id.rbWhy) {
                questionType = "为什么";
            } else if (checkedId == R.id.rbHowTo) {
                questionType = "怎么做";
            }
        });
    }
    
    /**
     * 旋转轮盘
     */
    private void spinRoulette() {
        // 禁用按钮，防止重复点击
        btnSpin.setEnabled(false);
        
        // 清除之前的超时任务
        if (timeoutRunnable != null) {
            timeoutHandler.removeCallbacks(timeoutRunnable);
        }
        
        // 根据转动次数更新状态
        if (spinCount == 0) {
            tvSpinStatus.setText("第一次转动中...");
            layoutResults.setVisibility(View.GONE);
            btnInterpret.setVisibility(View.GONE);
            tvFinalResult.setVisibility(View.GONE);
        } else if (spinCount == 1) {
            tvSpinStatus.setText("第二次转动中...");
        }
        
        // 生成随机旋转角度，确保至少旋转5圈
        float degrees = 1800 + random.nextFloat() * 360;
        
        // 创建旋转动画
        currentAnimator = ObjectAnimator.ofFloat(ivRoulette, "rotation", 0f, degrees);
        currentAnimator.setDuration(3000); // 3秒旋转
        currentAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
        
        // 设置超时机制
        timeoutRunnable = new Runnable() {
            @Override
            public void run() {
                // 超时处理：强制停止动画并显示结果
                if (currentAnimator != null && currentAnimator.isRunning()) {
                    currentAnimator.cancel();
                    handleSpinResult(degrees);
                    Toast.makeText(getContext(), "转盘超时，已自动停止", Toast.LENGTH_SHORT).show();
                }
            }
        };
        
        // 设置1分钟超时
        timeoutHandler.postDelayed(timeoutRunnable, TIMEOUT_DURATION);
        
        // 设置动画监听器
        currentAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                // 动画过程中可以添加声音效果等
            }
        });
        
        currentAnimator.addListener(new android.animation.AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(android.animation.Animator animation) {
                // 清除超时任务
                if (timeoutRunnable != null) {
                    timeoutHandler.removeCallbacks(timeoutRunnable);
                }
                
                // 动画正常结束，处理结果
                handleSpinResult(degrees);
            }
            
            @Override
            public void onAnimationCancel(android.animation.Animator animation) {
                // 动画被取消时也要清除超时任务
                if (timeoutRunnable != null) {
                    timeoutHandler.removeCallbacks(timeoutRunnable);
                }
            }
        });
        
        // 开始动画
        currentAnimator.start();
    }
    
    /**
     * 处理转盘结果
     */
    private void handleSpinResult(float degrees) {
        // 动画结束后，计算结果并显示
        float finalAngle = degrees % 360;
        int resultIndex = (int) (finalAngle / 45) % 8;
        
        if (spinCount == 0) {
            // 第一次转动结果
            firstGua = bagua[resultIndex];
            tvFirstResult.setText(firstGua);
            layoutResults.setVisibility(View.VISIBLE);
            tvSpinStatus.setText("第一次占卜结果：" + firstGua + "（" + baguaAttributes[resultIndex] + "）");
            
            // 准备第二次转动
            spinCount = 1;
            btnSpin.setText("再次转动");
            btnSpin.setEnabled(true);
        } else {
            // 第二次转动结果
            secondGua = bagua[resultIndex];
            tvSecondResult.setText(secondGua);
            
            // 确定64卦结果
            int firstIndex = -1;
            int secondIndex = -1;
            
            for (int i = 0; i < bagua.length; i++) {
                if (bagua[i].equals(firstGua)) {
                    firstIndex = i;
                }
                if (bagua[i].equals(secondGua)) {
                    secondIndex = i;
                }
            }
            
            // 查找对应的64卦
            int hexagramIndex = -1;
            for (int i = 0; i < hexagramIndices.length; i++) {
                if (hexagramIndices[i][0] == firstIndex && hexagramIndices[i][1] == secondIndex) {
                    hexagramIndex = i;
                    break;
                }
            }
            
            if (hexagramIndex != -1) {
                finalGua = hexagrams[hexagramIndex];
                tvFinalResult.setText(finalGua);
                tvFinalResult.setVisibility(View.VISIBLE);
                tvSpinStatus.setText("最终占卜结果：" + finalGua);
                btnInterpret.setVisibility(View.VISIBLE);
            } else {
                tvSpinStatus.setText("占卜结果计算错误，请重新开始");
            }
            
            // 重置状态
            btnSpin.setText("重新开始");
            btnSpin.setEnabled(true);
            spinCount = 0;
        }
    }
    
    /**
     * 解卦功能
     */
    private void interpretHexagram() {
        // 获取用户问题
        String question = etQuestion.getText().toString().trim();
        if (question.isEmpty()) {
            question = "求一卦";
        }
        
        // 构建AI解卦提示语
        String userMessage = "我刚刚进行了易经占卜，得到了" + finalGua + "卦。我的问题类型是\"" + questionType + 
                           "\"，具体问题是\"" + question + "\"。请你作为易经专家，详细解读这个卦象对我的启示。";
        
        // 显示加载对话框
        AlertDialog loadingDialog = new AlertDialog.Builder(requireContext())
                .setTitle("正在解卦")
                .setMessage("正在与AI沟通，请稍候...")
                .setCancelable(false)
                .show();

        // 设置解卦超时机制
        Handler interpretTimeoutHandler = new Handler();
        boolean[] isCompleted = {false}; // 使用数组来避免final变量限制
        
        Runnable interpretTimeoutRunnable = new Runnable() {
            @Override
            public void run() {
                if (!isCompleted[0] && isAdded() && getActivity() != null) {
                    isCompleted[0] = true;
                    getActivity().runOnUiThread(() -> {
                        if (isAdded() && getContext() != null) {
                            loadingDialog.dismiss();
                            Toast.makeText(getContext(), "解卦超时，请检查网络连接后重试", Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        };
        
        // 设置1分钟超时
        interpretTimeoutHandler.postDelayed(interpretTimeoutRunnable, TIMEOUT_DURATION);

        // 使用DeepSeek助手进行解卦
        DeepSeekHelper.getChatResponse(userMessage, new DeepSeekHelper.DeepSeekCallback() {
            @Override
            public void onResponse(String response) {
                if (!isCompleted[0] && isAdded() && getActivity() != null) {
                    isCompleted[0] = true;
                    interpretTimeoutHandler.removeCallbacks(interpretTimeoutRunnable);
                    getActivity().runOnUiThread(() -> {
                        if (isAdded() && getContext() != null) {
                            loadingDialog.dismiss();
                            showInterpretationDialog(response);
                        }
                    });
                }
            }

            @Override
            public void onError(String error) {
                if (!isCompleted[0] && isAdded() && getActivity() != null) {
                    isCompleted[0] = true;
                    interpretTimeoutHandler.removeCallbacks(interpretTimeoutRunnable);
                    getActivity().runOnUiThread(() -> {
                        if (isAdded() && getContext() != null) {
                            loadingDialog.dismiss();
                            Toast.makeText(getContext(), "解卦失败: " + error, Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        });
    }
    
    /**
     * 显示解卦对话框
     */
    private void showInterpretationDialog(String interpretation) {
        new AlertDialog.Builder(requireContext())
                .setTitle(finalGua + "卦解")
                .setMessage(interpretation)
                .setPositiveButton("关闭", null)
                .setNegativeButton("继续对话", (dialog, which) -> {
                    // 导航到AI聊天界面
                    Bundle args = new Bundle();
                    args.putString("initial_query", "关于" + finalGua + "卦，我想继续问...");
                    args.putString("initial_response", interpretation);
                    Navigation.findNavController(getView()).navigate(R.id.action_rouletteFragment_to_aiChatFragment, args);
                })
                .show();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        
        // 清理资源
        if (timeoutHandler != null && timeoutRunnable != null) {
            timeoutHandler.removeCallbacks(timeoutRunnable);
        }
        
        if (currentAnimator != null && currentAnimator.isRunning()) {
            currentAnimator.cancel();
        }
    }
}
